package com.cxyd.greenSite.utils;

import com.qiniu.util.Auth;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.*;
import java.util.UUID;

/**
 * @Author: huanglianyun
 * @Description:
 * @DATE: Created in 2019/11/26 14:37.
 */
public class QiniuDownloadUtil {

    public  static String accessKey = "dG1APUYoI37W_4X89PbNAIgEMa8cjSaeLXqDHGkG";
    public  static String secretKey = "b8yiUnAe7Jl8Dv9Xo-a6JKy1s_C4533OiW2d2Eil";

    //**************************下载文件**************************//
    //密钥配置
    public  static Auth auth = Auth.create(accessKey,secretKey);

    /**
     * 获取下载文件路径，即：donwloadUrl
     * @return
     */
    public static String getDownloadUrl(String targetUrl) {
        String downloadUrl = auth.privateDownloadUrl(targetUrl);
        String s = auth.privateDownloadUrl(targetUrl);
        return downloadUrl;
    }

    /**
     * 下载
     */
    public static void download(String targetUrl) {
        //获取downloadUrl
        String downloadUrl = getDownloadUrl(targetUrl);
        //本地保存路径
        String filePath = "D:\\hly\\2_test\\download\\";
        download(downloadUrl, filePath);
    }

    /**
     * 通过发送http get 请求获取文件资源
     * @param url
     * @param filepath
     * @return
     */
    public static void download(String url, String filepath) {
        OkHttpClient client = new OkHttpClient();
        System.out.println(url);
        Request req = new Request.Builder().url(url).build();
        Response resp = null;
        try {
            resp = client.newCall(req).execute();
            System.out.println(resp.isSuccessful());
            if(resp.isSuccessful()) {
                ResponseBody body = resp.body();
                InputStream is = body.byteStream();
                byte[] data = readInputStream(is);
                File imgFile = new File(filepath + UUID.randomUUID().toString() + ".docx");          //下载到本地的命名
                FileOutputStream fops = new FileOutputStream(imgFile);
                fops.write(data);
                fops.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Unexpected code " + resp);
        }
    }

    /**
     * 读取字节输入流内容
     * @param is
     * @return
     */
    private static byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        byte[] buff = new byte[1024 * 2];
        int len = 0;
        try {
            while((len = is.read(buff)) != -1) {
                writer.write(buff, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return writer.toByteArray();
    }
    //**************************下载文件**************************//

}
